<template>
  <div class="editor">
    <Button v-if="initing" type="primary" class="back-button" @click="back()" icon="md-arrow-back">返回上一级</Button>
    <Card v-if="initing">
      <Row>
        <Form ref="model" :model="model" :rules="ruleInline" inline :label-width="100">
          <Col span="14">
          <Row>
            <Col span="12">
            <FormItem prop="eventsName" label="赛事名称">
              <Input v-model="model.eventsName" v-show="isEdit" style="width:200px;" placeholder="请输入" />
              <span v-show="!isEdit" v-text="modelTemp.eventsName"></span>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem prop="kindCode" label="赛事类型">
              <dict code="ZGX_SSDJ" model="model.kindCode" :value="model.kindCode" @click="getVal" v-show="isEdit" style="width:200px;"></dict>
              <dict-span v-show="!isEdit" code="ZGX_SSDJ" :value="model.kindCode"></dict-span>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="12">
            <FormItem prop="eventsEnglishName" label="赛事英文名">
              <Input v-model="model.eventsEnglishName" v-show="isEdit" style="width:200px;" placeholder="请输入" />
              <span v-show="!isEdit" v-text="modelTemp.eventsEnglishName"></span>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem prop="niandu" label="赛事年度">
              <DatePicker v-model="model.niandu" v-show="isEdit" type="year" placeholder="请选择" clearable style="width: 200px"></DatePicker>
              <span v-show="!isEdit" v-text="modelTemp.niandu"></span>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="12">
            <FormItem prop="gradeCode" label="赛事级别">
              <dict model="model.gradeCode" :parentCode="model.kindCode" :value="model.gradeCode" code="ZGX_BSJB" @click="getVal" v-show="isEdit" style="width:200px;"></dict>
              <dict-span v-show="!isEdit" :parentCode="model.kindCode" code="ZGX_BSJB" :value="modelTemp.gradeCode"></dict-span>
            </FormItem>
            <!-- <FormItem prop="competitionState" label="赛事状态">
              <dict code="ZGX_SSZTSX" model="model.competitionState" :value="model.competitionState" @click="getVal" v-show="isEdit" style="width:200px;"></dict>
              <dict-span v-show="!isEdit" code="ZGX_SSZTSX" :value="modelTemp.competitionState"></dict-span>
            </FormItem> -->
            </Col>
            <Col span="12">
            <FormItem prop="planField" label="计划场次">
              <Input v-model="model.planField" v-show="isEdit" style="width:200px;" placeholder="请输入" />
              <span v-show="!isEdit" v-text="modelTemp.planField"></span>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="12">
            <FormItem prop="startTime" label="计划开始时间">
              <DatePicker type="date" v-show="isEdit" placeholder="请选择" style="width:200px; " v-model="model.startTime"></DatePicker>
              <span v-show="!isEdit" v-text="getTime(modelTemp.startTime)"></span>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem prop="endTime" label="计划结束时间">
              <DatePicker type="date" :options="opEndTime" v-show="isEdit" placeholder="请选择" style="width:200px;" v-model="model.endTime"></DatePicker>
              <span v-show="!isEdit" v-text="getTime(modelTemp.endTime)"></span>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="12">
            <FormItem prop="undertakingUnit" label="承办单位">
              <dict v-show="isEdit" model="model.undertakingUnit" :data="units" :value="model.undertakingUnit" code="CBDW" @click="getVal" style="width:200px;">
              </dict>
              <dict-span v-show="!isEdit" :data="units" :value="modelTemp.undertakingUnit" code="CBDW"></dict-span>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem prop="eventsType" label="比赛类型">
              <dict code="ZGX_BSLX" model="model.eventsType" :value="model.eventsType" @click="getVal" v-show="isEdit" style="width:200px;"></dict>
              <dict-span v-show="!isEdit" code="ZGX_BSLX" :value="modelTemp.eventsType"></dict-span>
            </FormItem>
            </Col>
          </Row>
          </Col>
          <Col span="10">
          <Row>
            <Col span="12">
            <FormItem prop="logo" style="width:90%;" label="赛事LOGO">
              <upload-logo v-show="isEdit" :value="model.logo" @upload="upload"></upload-logo>
              <div v-show="!isEdit" class="demo-upload-list">
                <img style="height:146px; width:146px; position: relative;" :src="modelTemp.logo" />
                <div v-show="modelTemp.logo" class="demo-upload-list-cover">
                  <Icon type="ios-eye-outline" @click.native="handleView(modelTemp.logo)"></Icon>
                </div>
              </div>
            </FormItem>
            </Col>
          </Row>
          </Col>
          <Col span="20">
          <Row>
            <Col>
            <FormItem prop="eventsIntroduce" style="width:89%;" label="赛事介绍">
              <editor v-show="isEdit" ref="editor" :value="model.eventsIntroduce" @on-change="handleChange" />
              <span v-show="!isEdit" v-html="$config.decodeHtml(modelTemp.eventsIntroduce)"></span>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col>
            <div class="right m-t-xl" style="width:89%;">
              <Button :to="'/game-apply-management/match/'+model.applyId" v-show="!isEdit&&applyId!=null">查看比赛安排</Button>
              <Button v-show="isEdit==true" @click="cancel">取消</Button>
              <Button v-show="isEdit==true" @click="save" class="m-l-md" type="primary">保存</Button>
              <Button v-show="isEdit==false" @click="edit" class="m-l-md" type="primary">编辑</Button>
            </div>
            </Col>
          </Row>
          </Col>
        </Form>
      </Row>
    </Card>
    <Card v-show="modelTemp.verifyStatus=='1'" v-if="initing" class="m-t-sm">
      <p slot="title">
        提交信息
      </p>
      <Row>
        <span>提交人：</span><span v-text="modelTemp.submissionBy"></span>
      </Row>
      <Row class="m-t-sm">
        <span>提交时间：</span><span v-text="$moment(modelTemp.submissionTime).format('YYYY-MM-DD HH:mm:ss')"></span>
      </Row>
      <Row class="m-t-sm">
        <span>提交说明：</span><span v-text="modelTemp.submissionExplain"></span>
      </Row>
    </Card>
    <spin-temp v-if="loading"></spin-temp>
    <Modal title="图片预览" v-model="visible" class="modal-img-view">
      <img :src="imgUrl" style="width: 100%;">
      <div slot="footer"></div>
    </Modal>
  </div>
</template>

<script>
import dict from "_c/dict/dict.vue";
import dictSpan from "_c/dict/dict-span.vue";
import uploadLogo from "_c/upload/upload-logo.vue";
import Editor from "_c/editor";
import _ from "lodash";
import Api from "@/api/game-apply";
import ApiGame from "@/api/game";
import { getDict } from "@/api/configure";
const api = new Api();
const apiGame = new ApiGame();
// 赛事管理
export default {
  components: {
    dict,
    dictSpan,
    uploadLogo,
    Editor
  },
  data() {
    return {
      initing: false,
      loading: false,
      isEdit: false,
      applyId: this.$route.params.id,
      type: this.$route.params.type,
      units: [],
      visible: false,
      imgUrl: null,
      opEndTime: {
        disabledDate: date => {
          let self = this;
          return (
            date &&
            self.model.startTime &&
            self.model.startTime.valueOf() > date.valueOf()
          );
        }
      },
      model: {
        applyId: this.$route.params.id,
        kindCode: "1",
        eventsType: "1",
        createBy: this.$store.state.userId
      },
      modelTemp: {},
      ruleInline: {
        eventsName: [
          {
            required: true,
            message: "请输入",
            trigger: "blur"
          },
          {
            max: this.$config.INPUT_SIZE,
            message: `最多输入${this.$config.INPUT_SIZE}个字符`,
            trigger: "blur"
          }
        ],
        eventsEnglishName: [
          {
            type: "string",
            max: this.$config.INPUT_ENGLISH_SIZE,
            message: `最多输入${this.$config.INPUT_ENGLISH_SIZE}个字符`
          }
        ],
        niandu: [{ required: true, message: "请选择" }],
        gradeCode: [{ required: true, message: "请选择" }],
        kindCode: [{ required: true, message: "请选择" }],
        // competitionState: [{ required: true, message: "请选择" }],
        planField: [
          { required: true, message: "请输入" },
          {
            pattern: this.$config.numReg,
            message: "请输入数字",
            trigger: "blur"
          },
          {
            max: this.$config.INPUT_NUMBER_SIZE,
            message: `数字最长为${this.$config.INPUT_NUMBER_SIZE}位`,
            transform(value) {
              return value == null ? "" : value.toString();
            }
          }
        ],
        startTime: [
          { required: true, type: "date", message: "请选择", trigger: "change" }
        ],
        endTime: [
          { required: true, type: "date", message: "请选择", trigger: "change" }
        ],
        eventsType: [{ required: false, message: "请选择" }],
        undertakingUnit: [{ required: true, message: "请选择" }],
        logo: [{ required: false, message: "请选择赛事LOGO" }],
        eventsIntroduce: [
          {
            required: false,
            type: "string",
            message: "请输入",
            trigger: "change"
          }
        ]
      }
    };
  },
  mounted() {
    let self = this;
    getDict({ code: "CBDW" })
      .then(data => {
        self.units = data;
        self.initing = true;
        self.getGameById();
      })
      .catch(error => {
        self.initing = true;
        self.getGameById();
      });
  },
  watch: {
    "model.startTime": function(newVal) {
      let self = this;
      if (newVal != null && newVal.valueOf() > self.model.endTime.valueOf()) {
        self.model.endTime = null;
      }
    }
  },
  methods: {
    back() {
      let path = "/game-management/";
      // 中高协 跳待审核页面
      if (this.$store.state.user.access.includes("GAME_MANAGE")) {
        path = "/game-verify-management/game-audit";
      } else {
        let { kindCode } = this;
        switch (kindCode) {
          case "1":
            path += "career/man";
            break;
          case "2":
            path += "career/women";
            break;
          case "3":
            path += "history/amateur/man";
            break;
          case "4":
            path += "history/amateur/women";
            break;
          case "5":
            path += "history/teen/man-a";
            break;
          case "6":
            path += "history/teen/women-a";
            break;
          case "7":
            path += "history/teen/man-b";
            break;
          case "8":
            path += "history/teen/women-b";
            break;
          default:
            path += "career/man";
            break;
        }
      }
      this.$router.push({ path });
    },
    handleView(url) {
      this.imgUrl = url;
      this.visible = true;
    },
    getTime(timeStr) {
      if (timeStr == null) {
        return "";
      }
      return this.$moment(timeStr).format("YYYY-MM-DD");
    },
    // 获取字典选择的值
    getVal(expression) {
      let self = this;
      eval(expression);
      self.$forceUpdate();
    },
    // 获取文件上传地址
    upload(url) {
      this.model.logo = url;
      this.$refs["model"].validateField("logo");
    },
    // 获取数据
    getGameById() {
      let self = this;
      if (_.isEmpty(self.applyId)) {
        self.isEdit = true;
        return;
      }
      self.loading = true;
      let primary = null;
      if (self.type === "copy") {
        //赛事id
        primary = apiGame.getGameById(self.applyId);
      } else {
        primary = api.getGameById(self.applyId);
      }
      primary
        .then(data => {
          self.modelTemp = data;
          self.modelTemp.updateBy = self.$store.state.userId;
          if (
            !["0", "3"].includes(data.verifyStatus) ||
            data.operationType === "3"
          ) {
            self.isEdit = null;
          }
          self.loading = false;
        })
        .catch(error => {
          self.loading = false;
        });
    },
    // 分页
    changePage(pageNum) {
      this.page.current = pageNum;
      this.fetchList();
    },
    save() {
      let self = this;
      self.$refs["model"].validate(valid => {
        if (valid) {
          self.loading = true;
          self.model.niandu = self.$moment(self.model.niandu).format("YYYY");
          if (self.model.operationType == null) {
            if (self.model.eventsId == null) {
              self.model.operationType = 1;
            } else if (self.model.eventsId != null) {
              self.model.operationType = 2;
            }
          }
          self.model = _.omit(self.model, ["verifyStatus"]);
          api
            .edit(self.model)
            .then(data => {
              if (data) {
                this.$router.go(-1);
              }
              self.loading = false;
            })
            .catch(error => {
              self.loading = false;
            });
        }
      });
    },
    edit() {
      let self = this;
      self.model = _.omit({ ...self.modelTemp }, [
        "weiWriteCount",
        "yiWriteCount",
        "submissionExplain",
        "submissionTime",
        "submissionBy"
      ]);
      self.$refs.editor.setHtml(
        this.$config.decodeHtml(self.model.eventsIntroduce)
      );
      self.isEdit = true;
      self.$forceUpdate();
    },
    cancel() {
      let self = this;
      if (self.applyId) {
        self.$refs["model"].resetFields();
        self.$refs.editor.setHtml("");
        self.isEdit = false;
        self.$forceUpdate();
        return;
      }
      self.$router.go(-1);
    },
    handleChange(html, text) {
      if (text !== "" || /<iframe|<img/.test(html)) {
        this.model.eventsIntroduce = html;
      } else {
        this.model.eventsIntroduce = "";
      }
      this.$refs["model"].validateField("eventsIntroduce");
    }
  }
};
</script>


